use std::fs;
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};

fn main() {
    //创建tcp监听器
    let listen = TcpListener::bind("127.0.0.1:7878").unwrap();
    //循环监听器获取到的请求
    for stream in listen.incoming() {
        //处理请求
        let stream= stream.unwrap();
        handle_connection(stream);
    }

}
fn  handle_connection(mut stream: TcpStream) {
    //读取请求
    let mut buffer = [0; 1024];
    //unwrap() 什么作用
    stream.read(&mut buffer).unwrap();
    //&buffer[..] 表示buffer的第一个元素到buffer的最后一个元素，也就是buffer中的所有元素
    println!("request:{}", String::from_utf8_lossy(&buffer[..]));

    let content = fs::read_to_string("hello.html").unwrap();
    let response = format!("HTTP/1.1 200 OK\r\n\r\n{}", content);
    stream.write(response.as_bytes()).unwrap();
    stream.flush().unwrap();

    // //解析请求
    // let get = b"GET / HTTP/1.1\r\n";
    // let (status_line, filename) = if buffer.starts_with(get) {
    //     ("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
    // }
}

